<template>
  <q-page padding>
    <q-card flat bordered class="exhibition-form-card">
      <q-card-section class="row items-center justify-between">
        <div class="row items-center">
          <q-btn
            icon="arrow_back"
            flat
            round
            dense
            class="q-mr-sm"
            @click="handleCancel"
          />
          <div class="text-h6">{{ isEdit ? '编辑展会信息' : '新增展会信息' }}</div>
        </div>
        <q-btn
          v-if="isEdit && route.query.mode !== 'view'"
          :label="isEditing ? '取消编辑' : '编辑'"
          :color="isEditing ? 'grey' : 'primary'"
          @click="toggleEdit"
        />
      </q-card-section>

      <q-card-section class="scroll-content">
        <q-form ref="formRef" @validation-error="onValidationError" @validation-success="onValidationSuccess">
          <!-- 添加AI检查状态提示 -->
          <div class="ai-check-alert q-mb-md" v-if="formData.ai_checked_status !== undefined">
            <q-banner
              :class="{
                'bg-grey-2': formData.ai_checked_status === 0,
                'bg-green-1': formData.ai_checked_status === 1,
                'bg-orange-1': formData.ai_checked_status === 2
              }"
              class="ai-check-banner"
              rounded
            >
              <template v-slot:avatar>
                <q-icon
                  :name="formData.ai_checked_status === 0 ? 'pending' : formData.ai_checked_status === 1 ? 'check_circle' : 'warning'"
                  :class="{
                    'text-grey': formData.ai_checked_status === 0,
                    'text-positive': formData.ai_checked_status === 1,
                    'text-warning': formData.ai_checked_status === 2
                  }"
                  size="md"
                />
              </template>
              <div class="ai-check-content">
                <div class="ai-check-status" :class="{
                  'text-grey-8': formData.ai_checked_status === 0,
                  'text-positive': formData.ai_checked_status === 1,
                  'text-warning': formData.ai_checked_status === 2
                }">
                  {{ formData.ai_checked_status === 0 ? '未检查' : formData.ai_checked_status === 1 ? '检查无误' : '检查有问题' }}
                </div>
                <template v-if="formData.ai_checked_status !== 0">
                  错误：<div class="ai-check-description" v-if="formData.error_check_description">
                    {{ formData.error_check_description }}
                  </div>
                  建议：<div class="ai-check-description" v-if="formData.advice_check_description">
                    {{ formData.advice_check_description }}
                  </div>
                </template>
              </div>
            </q-banner>
          </div>

          <div class="row q-col-gutter-md">
            <!-- 修改上传组件 -->
            <div class="col-12 col-md-3">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">Logo图片</div>
                <div class="field-value">
                  <q-avatar
                    v-if="formData.logo"
                    size="24px"
                    class="cursor-pointer"
                    @click="$q.dialog({
                      component: 'img',
                      componentProps: {
                        src: formData.logo
                      }
                    })"
                  >
                    <img :src="formData.logo" />
                  </q-avatar>

                </div>
              </template>
              <q-file
                v-else
                v-model="photoFile"
                label="Logo图片"
                accept=".jpg, .png"
                @update:model-value="onPhotoSelected"
                :rules="[val => !!val || '请上传logo']"

              >
                <template v-slot:append>
                  <q-avatar
                    v-if="formData.logo"
                    size="24px"
                    class="cursor-pointer q-my-auto"
                    @click.stop="$q.dialog({
                      component: 'img',
                      componentProps: {
                        src: formData.logo
                      }
                    })"
                  >
                    <img :src="formData.logo" />
                  </q-avatar>
                </template>
              </q-file>
            </div>
            <div class="col-12 col-md-3">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">审批系统展会编号</div>
                <div class="field-value">{{ formData.exhibition_number }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.exhibition_number"
                label="审批系统展会编号"
                :rules="[
                  val => !!val || '请输入审批系统展会编号',
                  val => /^\d{1,8}$/.test(val) || '审批系统展会编号必须是1-8位数字'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">中文名称</div>
                <div class="field-value">{{ formData.chinese_name }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.chinese_name"
                label="中文名称"
                :rules="[
                  val => !!val || '请输入中文名称',
                  val => /^[\u4e00-\u9fa5A-Z、]+$/.test(val) || '中文名称只能包含汉字、英文大写字母和顿号',
                  val => val.startsWith(formData.country) || `展会名称建议以国别（${formData.country}）开头`
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">外文全称</div>
                <div class="field-value">{{ formData.english_name }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.english_name"
                label="外文全称"
                :rules="[
                  val => !!val || '请输入外文全称',
                  val => /^[0-9A-Z. +\-'()&,]+$/.test(val) || '外文全称只能包含大写字母、数字、点、空格、连字符、括号、逗号和&符号'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">外文简称</div>
                <div class="field-value">{{ formData.english_short_name || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.english_short_name"
                label="外文简称"
                :rules="[
                  val => !val || /^[0-9A-Z. +\-]+$/.test(val) || '外文简称只能包含大写字母、数字、点、空格和连字符',
                  val => !val || val !== formData.english_name || '外文简称不能与全称相同'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">举办时间</div>
                <div class="field-value">{{ formData.holding_time }}</div>
              </template>
              <div v-else class="row q-col-gutter-sm">
                <div class="col-12">
                  <q-select
                    v-model="holding_time_type"
                    :options="[
                      { label: '标准格式', value: 'standard' },
                      { label: '自定义格式', value: 'custom' }
                    ]"
                    label="举办时间"
                    emit-value
                    map-options
                  />
                </div>
                <div class="col-12">
                  <q-input
                    v-model="formData.holding_time"
                    label=""
                    :rules="[
                      val => !!val || '请输入举办时间',
                      val => {
                        if (holding_time_type.value === 'standard') {
                          return /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/.test(val) || '举办时间格式为：数字月数字日-数字月数字日'
                        }
                        return true
                      }
                    ]"
                    @blur="handleHoldingTimeBlur"
                  />
                </div>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">洲</div>
                <div class="field-value">{{ formData.continent || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.continent"
                :options="Object.keys(regionMap)"
                label="洲"
                :rules="isFirstLoad ? [] : [val => !!val || '请选择洲']"
                clearable
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">国家</div>
                <div class="field-value">{{ formData.country || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.country"
                :options="filteredCountries"
                label="国家"
                :disable="!formData.continent"
                :rules="isFirstLoad ? [] : [val => !!val || '请选择国家']"
                clearable
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">城市</div>
                <div class="field-value">{{ formData.city || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.city"
                :options="filteredCities"
                label="城市"
                :disable="!formData.country"
                :rules="isFirstLoad ? [] : [val => !!val || '请选择城市']"
                clearable
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">举办频率</div>
                <div class="field-value">{{ formData.frequency || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.frequency"
                :options="['一年一届', '一年两届', '一年四届', '两年一届', '三年一届', '四年一届']"
                label="举办频率"
                :rules="[val => !!val || '请选择举办频率']"
              />
            </div>

            <div class="col-12 col-md-3">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">行业</div>
                <div class="field-value">{{ formData.industry || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.industry"
                :options="filteredIndustries"
                label="行业"
                :rules="[val => !!val || '请选择行业']"
                use-input
                input-debounce="0"
                @filter="filterIndustry"
                @input-value="val => inputValue = val"
                hide-selected
                fill-input
                clearable
              />
            </div>
            <div class="col-12 col-md-3">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">AI行业检查</div>
                <div class="field-value">{{ formData.industry_ai || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.industry_ai"
                :options="filteredIndustries"
                label="AI行业检查"
                :rules="[val => !!val || '请选择行业']"
                use-input
                input-debounce="0"
                @filter="filterIndustry"
                @input-value="val => inputValue = val"
                hide-selected
                fill-input
                clearable
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">主办方</div>
                <div class="field-value">{{ formData.organizer || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.organizer"
                label="主办方"
                :rules="[
                  val => !val || /^[\u4e00-\u9fa5A-Za-zÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ&.、 ()]+$/.test(val) || '主办方名称只能包含汉字、大小写字母、德语字母和顿号'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">主办方外文</div>
                <div class="field-value">{{ formData.organizer_en || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.organizer_en"
                label="主办方外文"
                :rules="[
                  val => !val || /^[a-zA-Z&.,/ ()ÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ\-']+$/.test(val) || '主办方英文名称格式不正确'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">联系方式</div>
                <div class="field-value">{{ formData.contact_info || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.contact_info"
                label="联系方式"
                :rules="[
                  val => !val || /^(\+\d+ \(\d+\) \d{1,4}-\d{4,8}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/.test(val) || '联系方式格式需要是电话号码(+xx (xx) xxx-xxxx)或邮箱地址(xxx@xxx.xxx)'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">展馆</div>
                <div class="field-value">{{ formData.exhibition_hall || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.exhibition_hall"
                label="展馆"
                :rules="[
                  val => !!val || '请输入展馆',
                  val => val.startsWith(formData.city) || `展馆名称必须以城市名（${formData.city}）开头`
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">展馆外文</div>
                <div class="field-value">{{ formData.exhibition_hall_english || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.exhibition_hall_english"
                label="展馆外文"
                :rules="[
                  val => !!val || '请输入展馆英文名称',
                  val => /^[A-Za-z\-'ÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ&., ]+$/.test(val) || '展馆英文名称格式不正确'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">官网</div>
                <div class="field-value">{{ formData.official_website || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.official_website"
                label="官网"
                :rules="[
                  val => !val || /^(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]+(?:\/[a-zA-Z0-9-_/]*)?(?:\.[a-z]+)?$/.test(val) || '官网格式不正确'
                ]"
              />
            </div>

            <div class="col-12">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">展品范围</div>
                <div class="field-value field-value-multiline">{{ formData.exhibit_scope || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.exhibit_scope"
                type="textarea"
                label="展品范围"
                :rules="[
                  val => !!val || '请输入展品范围',
                  val => val?.length <= 100 || '展品范围不能超过100字',
                  val => !val?.endsWith('。') || '展品范围不能以句号结尾',
                  val => val === val?.trim() || '展品范围不能有前后空格'
                ]"
                autogrow
              />
            </div>

            <div class="col-12">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">简介</div>
                <div class="field-value field-value-multiline">{{ formData.description || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.description"
                type="textarea"
                label="简介"
                :rules="[
                  val => !val || val?.length <= 150 || '简介不能超过150字',
                  val => !val?.endsWith('。') || '简介不能以句号结尾',
                  val => !val || val === val?.trim() || '简介不能有前后空格'
                ]"
                autogrow
              />
            </div>



            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">是否UFI认证</div>
                <div class="field-value">{{ ufiOptions.find(o => o.value === formData.ufi_certified)?.label || '-' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.ufi_certified"
                :options="ufiOptions"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                label="是否UFI认证"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">展会面积</div>
                <div class="field-value">{{ formData.exhibition_area ? `${formData.exhibition_area} ㎡` : '-' }}</div>
              </template>
              <q-input
                v-else
                v-model.number="formData.exhibition_area"
                label="展会面积"
                suffix="㎡"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">是否供应链重点展会</div>
                <div class="field-value">{{ formData.is_supply_chain || '否' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.is_supply_chain"
                :options="[
                  { label: '否', value: '否' },
                  { label: '是', value: '是' }
                ]"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                label="是否供应链重点展会"
              />
            </div>

            <div class="col-12 col-md-6">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">是否CCPIT展会</div>
                <div class="field-value">{{ formData.is_ccpit || '否' }}</div>
              </template>
              <q-select
                v-else
                v-model="formData.is_ccpit"
                :options="[
                  { label: '否', value: '否' },
                  { label: '是', value: '是' }
                ]"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                label="是否CCPIT展会"
              />
            </div>


                        <!-- 添加备注字段 -->
                        <div class="col-12">
              <template v-if="isEdit && !isEditing">
                <div class="field-label">备注</div>
                <div class="field-value field-value-multiline">{{ formData.remarks || '-' }}</div>
              </template>
              <q-input
                v-else
                v-model="formData.remarks"
                type="textarea"
                label="备注"
                :rules="[
                  val => !val || val?.length <= 200 || '备注不能超过200字'
                ]"
                autogrow
              />
            </div>
          </div>
        </q-form>
        
        <!-- 添加滚动指示器 -->
        <div class="scroll-indicator" ref="scrollIndicator" v-show="showScrollIndicator">
          <q-icon name="keyboard_arrow_down" size="sm" />
          <span>滑动查看更多</span>
        </div>
      </q-card-section>
      
      <!-- 固定在底部的按钮区域 -->
      <q-card-actions class="fixed-bottom-actions" v-if="!isEdit || isEditing">
        <q-space />
        <q-btn
          label="取消"
          color="grey"
          flat
          class="q-mr-sm"
          @click="confirmCancel"
        />
        <q-btn
          label="保存"
          color="primary"
          @click="handleSubmit"
        />
      </q-card-actions>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useQuasar } from 'quasar'
// 导入部分添加新的 API
import { getExhibition, updateExhibition, getRegionMap, getIndustryMap } from 'src/api/exhibition'
import { uploadApi } from 'src/api/upload'

const $q = useQuasar()
const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEdit = ref(false)
const holding_time_type = ref('standard')  // 添加这一行
const photoFile = ref(null)

// 添加滚动指示器相关变量
const scrollIndicator = ref(null)
const showScrollIndicator = ref(false)
const scrollContent = ref(null)

const ufiOptions = [
  { label: '未知', value: 0 },
  { label: '是', value: 1 },
  { label: '否', value: 2 }
]

const formData = ref({
  logo:'',
  exhibition_number: '',
  chinese_name: '',
  english_name: '',
  english_short_name: '',
  holding_time: '',
  event_date_end: '',
  event_date_start:'',
  continent: '',
  country: '',
  city: '',
  frequency: '',
  industry: '',
  industry_ai: '',
  organizer: '',
  organizer_en: '',
  contact_info: '',
  exhibition_hall: '',
  exhibition_hall_english: '',
  official_website: '',
  exhibit_scope: '',
  description: '',
  ufi_certified: 0,  // 设置默认值为 0（未知）
  exhibition_area: null,
  is_supply_chain: '否',  // 新增字段
  is_ccpit: '否',        // 新增字段
  ai_checked_status: 0,  // 添加AI检查状态，默认为未检查
  error_check_description: '',
  advice_check_description: '',  // 添加AI检查描述
  remarks: ''  // 新增备注字段
})

// 将静态数据替换为动态获取的数据
const industryTypes = ref([])

// 添加获取行业数据的方法
const fetchIndustryMap = async () => {
  try {
    const res = await getIndustryMap()
    industryTypes.value = res.data
  } catch (error) {
    console.error('获取行业数据失败:', error)
    $q.notify({
      type: 'negative',
      message: '获取行业数据失败'
    })
  }
}

const onPhotoSelected = async (file) => {
  if (!file) return

  try {
    const response = await uploadApi.uploadFile(file, 'logos')

    if (response.data.code === 200) {
      formData.value.logo = response.data.data.path
      $q.notify({
        type: 'positive',
        message: '照片上传成功'
      })
    } else {
      throw new Error(response.data.message)
    }
  } catch (error) {
    console.error('照片上传失败:', error)
    $q.notify({
      type: 'negative',
      message: '照片上传失败：' + (error.response?.data?.message || error.message)
    })
    photoFile.value = null
  }
}

// 在 setup 中添加
const isFirstLoad = ref(true)

// 添加一个方法来处理动态添加地区数据
const updateRegionMap = () => {
  if (isFirstLoad.value && formData.value.continent && formData.value.country) {
    if (!regionMap.value[formData.value.continent]) {
      regionMap.value[formData.value.continent] = {}
    }
    if (!regionMap.value[formData.value.continent][formData.value.country]) {
      regionMap.value[formData.value.continent][formData.value.country] = []
    }
    if (formData.value.city &&
        !regionMap.value[formData.value.continent][formData.value.country].includes(formData.value.city)) {
      regionMap.value[formData.value.continent][formData.value.country].push(formData.value.city)
    }
  }
}

// 修改 getExhibitionDetail 函数
const getExhibitionDetail = async (id) => {
  console.log('getExhibitionDetail', id)
  try {
    const res = await getExhibition(id)
    console.log('getExhibitionDetail', res)
    const data = { ...res.data }
    // 确保 ufi_certified 是数字类型
    data.ufi_certified = Number(data.ufi_certified || 0)
    Object.assign(formData.value, data)
    isFirstLoad.value = true  // 设置为首次加载状态
    updateRegionMap()  // 添加这一行
    // 判断举办时间格式并设置对应的类型
    if (data.holding_time) {
      const standardPattern = /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/
      holding_time_type.value = standardPattern.test(data.holding_time) ? 'standard' : 'custom'
    }
  } catch (error) {
    console.error(error)
    $q.notify({
      type: 'negative',
      message: '获取展会信息失败'
    })
  }
}


const isEditing = ref(false)
// 监听编辑状态变化
watch(isEditing, (newVal) => {
  if (newVal) {
    isFirstLoad.value = false  // 进入编辑状态时关闭首次加载标记
  }
})

// 添加切换编辑状态的方法
const toggleEdit = () => {
  isEditing.value = !isEditing.value

  // 当进入编辑状态时，触发所有字段的表单验证
  if (isEditing.value) {
    // 使用nextTick确保DOM已完全更新
    nextTick(() => {
      // 首先运行一次整体验证
      formRef.value.validate()

      // 然后等待组件更新完成后再进行一次更详细的验证
      setTimeout(() => {
        // 找到所有表单控件元素
        const formControls = formRef.value.$el.querySelectorAll('.q-field')

        // 对每一个表单控件执行"触摸"操作，这会触发验证
        formControls.forEach(control => {
          // 已经验证过的不需要重复验证
          if (!control.classList.contains('q-field--error')) {
            // 获取内部的输入元素
            const inputElement = control.querySelector('input') ||
                                control.querySelector('textarea') ||
                                control.querySelector('.q-field__native')

            // 如果找到了输入元素，触发聚焦和失焦事件
            if (inputElement) {
              // 模拟聚焦然后立即失焦
              inputElement.focus()
              inputElement.blur()
            } else {
              // 对于无法找到输入元素的复杂组件(如q-select)，通过添加和移除类来触发验证
              control.classList.add('q-field--focused')
              control.classList.remove('q-field--focused')
              control.classList.add('q-field--touched')
            }
          }
        })

        // 最后再次运行整体验证确保所有规则生效
        formRef.value.validate()
      }, 100)
    })
  }
}

// 添加表单验证事件处理函数
const onValidationError = () => {
  console.log('表单验证失败，请检查输入内容');
}

const onValidationSuccess = () => {
  console.log('表单验证成功');
}

// 修改 filterIndustry 函数
const inputValue = ref('')
const filteredIndustries = ref([...industryTypes.value])

const filterIndustry = (val, update) => {
  if (!val) {
    update(() => {
      filteredIndustries.value = [...industryTypes.value]
    })
    return
  }

  update(() => {
    const needle = val.toLowerCase()
    filteredIndustries.value = industryTypes.value.filter(v =>
      v.toLowerCase().includes(needle)
    )
  })
}



// 修改 handleSubmit
const handleSubmit = async () => {
  try {
    // 先检查举办时间格式
    if (holding_time_type.value === 'standard') {
      const timePattern = /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/
      if (!timePattern.test(formData.value.holding_time)) {
        $q.notify({
          type: 'negative',
          message: '举办时间格式错误，请修正后再提交'
        })
        return
      }
    }

    console.log('formData.value', formData.value)
    const submitData = { ...formData.value }
    if (isEdit.value) {
      const response = await updateExhibition(formData.value.id, submitData)
      console.log(response)
      console.log(response.status)
      if (!response.data.error) {
        $q.notify({
          type: 'positive',
          message: '更新成功'
        })
        isEditing.value = false  // 保存成功后退出编辑状态
        router.push('/exhibition')
      } else {
        // 显示后端返回的具体错误信息
        $q.notify({
          type: 'negative',
          message: response.data.error || '保存失败'
        })
      }

    }
    router.push('/exhibition')
  } catch (error) {
    console.log(error)
    $q.notify({
      type: 'negative',
      message: '保存失败'
    })
  }
}

// 修改 confirmCancel
const confirmCancel = () => {
  const message = isEdit.value ?
    (isEditing.value ? '确定要取消编辑吗？未保存的内容将会丢失' : '确定要返回列表页吗？') :
    '确定要取消编辑吗？未保存的内容将会丢失'

  $q.dialog({
    title: '确认提示',
    message,
    persistent: true,
    ok: {
      label: '确定',
      color: 'primary'
    },
    cancel: {
      label: '取消',
      color: 'grey'
    }
  }).onOk(async () => {
    if (isEdit.value && isEditing.value) {
      isEditing.value = false
      // 重新加载数据并确保UI刷新后生效
      await getExhibitionDetail(route.query.id)
    } else {
      handleCancel()
    }
  })
}

const handleCancel = () => {
  router.push({
    path: '/exhibition',
    replace: true
  })
}

// 将 regionMap 改为空对象初始值
const regionMap = ref({})

// 添加获取地区数据的方法
const fetchRegionMap = async () => {
  try {
    const res = await getRegionMap()
    regionMap.value = res.data
  } catch (error) {
    console.error('获取地区数据失败:', error)
    $q.notify({
      type: 'negative',
      message: '获取地区数据失败'
    })
  }
}

// 监测滚动区域是否需要显示指示器
const checkScrollIndicator = () => {
  if (!scrollContent.value) return
  
  const el = scrollContent.value
  const hasScrollbar = el.scrollHeight > el.clientHeight
  const isSmallScreen = window.innerHeight < 700
  
  showScrollIndicator.value = hasScrollbar && isSmallScreen && el.scrollTop < 100
}

// 添加滚动处理函数
const handleScroll = () => {
  if (!scrollContent.value) return
  
  // 当用户向下滚动超过一定距离后，隐藏指示器
  if (scrollContent.value.scrollTop > 100) {
    showScrollIndicator.value = false
  } else {
    checkScrollIndicator()
  }
}

// 修改 onMounted，添加获取地区数据和行业数据的调用
onMounted(async () => {
  // 获取滚动区域元素
  scrollContent.value = document.querySelector('.scroll-content')
  
  // 窗口大小变化时重新检查
  window.addEventListener('resize', checkScrollIndicator)
  
  // 添加滚动事件监听
  if (scrollContent.value) {
    scrollContent.value.addEventListener('scroll', handleScroll)
  }
  
  // 初始检查
  setTimeout(checkScrollIndicator, 500)
  
  await fetchRegionMap() // 先获取地区数据
  await fetchIndustryMap() // 获取行业数据
  const id = route.params.id
  if (id) {
    isEdit.value = true
    await getExhibitionDetail(id)

    // 检查是否有 mode 查询参数，并根据其值设置编辑状态
    const mode = route.query.mode
    if (mode === 'edit') {
      // 如果 mode 是 'edit'，则自动进入编辑模式
      isEditing.value = true
    }
    // 如果 mode 是 'view'，则保持原来的非编辑模式
  } else {
    // 如果是新增表单，确保在DOM更新后进行首次验证
    nextTick(() => {
      formRef.value.validate()
    })
  }
  
  // 表单加载完成后再次检查是否需要显示滚动指示器
  setTimeout(checkScrollIndicator, 1000)
})

// 组件卸载时，移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', checkScrollIndicator)
  
  // 移除滚动事件监听
  if (scrollContent.value) {
    scrollContent.value.removeEventListener('scroll', handleScroll)
  }
})

// 添加计算属性：根据开始和结束时间生成 holding_time
const computedHoldingTime = computed(() => {
  if (!formData.value.event_date_start || !formData.value.event_date_end) {
    return ''
  }

  const startDate = new Date(formData.value.event_date_start)
  const endDate = new Date(formData.value.event_date_end)

  return `${startDate.getMonth() + 1}月${startDate.getDate()}日-${endDate.getMonth() + 1}月${endDate.getDate()}日`
})

// 监听计算属性的变化，更新 holding_time
watch(computedHoldingTime, (newValue) => {
  formData.value.holding_time = newValue
})

// 监听 holding_time 的变化，更新开始和结束时间
watch(() => formData.value.holding_time, (newValue) => {
  if (!newValue) return

  // 只有在标准格式下才尝试解析日期
  if (holding_time_type.value === 'standard') {
    const match = newValue.match(/^(\d+)月(\d+)日-(\d+)月(\d+)日$/)
    if (match) {
      const [_, startMonth, startDay, endMonth, endDay] = match
      const currentYear = new Date().getFullYear()

      formData.value.event_date_start = `${currentYear}-${String(startMonth).padStart(2, '0')}-${String(startDay).padStart(2, '0')} 00:00:00`
      formData.value.event_date_end = `${currentYear}-${String(endMonth).padStart(2, '0')}-${String(endDay).padStart(2, '0')} 00:00:00`
    }
  }

  // 不在输入过程中触发验证，改为仅在编辑模式下且手动触发时验证
  // 注释掉自动验证的代码，避免焦点跳转
  // if (isEditing.value) {
  //   nextTick(() => formRef.value.validate())
  // }
})

// 添加对holding_time_type的监听，因为它影响举办时间的验证
watch(holding_time_type, () => {
  // 移除自动验证，避免在切换模式时导致焦点跳转
  // if (isEditing.value) {
  //   nextTick(() => formRef.value.validate())
  // }
})

// 添加一个处理holding_time失焦事件的方法
const handleHoldingTimeBlur = () => {
  // 仅在编辑模式下，手动验证此字段，但不执行整个表单的验证
  if (isEditing.value) {
    if (holding_time_type.value === 'standard') {
  // 在这种模式下写代码 触发举办时间的焦点的 格式验证的警告  当未标准格式时候
  }
    // 这里可以进行单独验证，但不会影响焦点
    // 如果需要，可以在这里添加更多逻辑
  }
}

// 修改计算属性，移除副作用
const filteredCountries = computed(() => {
  if (!formData.value.continent) return []
  return Object.keys(regionMap.value[formData.value.continent] || {})
})

const filteredCities = computed(() => {
  if (!formData.value.continent || !formData.value.country) return []
  return regionMap.value[formData.value.continent]?.[formData.value.country] || []
})

// 修改监听器，仅在非首次加载时清空值
watch(() => formData.value.continent, () => {
  if (!isFirstLoad.value) {
    formData.value.country = ''
    formData.value.city = ''
    // 如果在编辑模式，触发验证
    if (isEditing.value) {
      nextTick(() => formRef.value.validate())
    }
  }
})

watch(() => formData.value.country, () => {
  if (!isFirstLoad.value) {
    formData.value.city = ''
    // 如果在编辑模式，触发验证
    if (isEditing.value) {
      nextTick(() => formRef.value.validate())
    }
  }
})




// ... 修改模板部分
</script>

<style>
.q-field--disabled {
  cursor: default !important;
  opacity: 1 !important;
}
.q-field--disabled * {
  cursor: default !important;
  color: #000000 !important;
}
.q-field--disabled .q-field__label {
  color: rgba(0, 0, 0, 0.8) !important;
}

/* Add styles for input text to be pure black */
.q-field__native,
.q-field__input {
  color: #000000 !important;
}

/* Ensure placeholder text remains visible but distinct */
::placeholder {
  color: rgba(0, 0, 0, 0.5) !important;
}

/* AI检查提示样式 */
.ai-check-alert {
  .ai-check-banner {
    padding: 16px;
    transition: all 0.3s ease;

    &:deep(.q-banner__avatar) {
      min-width: 48px;
    }

    .q-icon {
      font-size: 32px;
    }
  }

  .ai-check-content {
    .ai-check-status {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 4px;
    }

    .ai-check-description {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      white-space: pre-line;
    }
  }
}

/* 修改验证规则提示的颜色 */
.q-field__messages {
  color: #c5735a !important;
}

.q-field--error .q-field__control {
  color: #7a7976 !important;
}

/* 去掉错误状态下的感叹号图标 */
.q-field--error .q-field__bottom .q-field__messages i,
.q-field__bottom .q-field__counter i {
  display: none !important;
}

/* 确保表单验证错误图标不显示 */
.q-field--error:before {
  display: none !important;
}

/* 修改错误提示文字为橙色 */
.q-field--error .q-field__messages {
  color: #ff8800 !important;
}

/* 移除错误状态下的边框变化 */
.q-field--error .q-field__control {
  box-shadow: none !important;
  border-color: rgba(0, 0, 0, 0.2) !important;
}

/* 隐藏输入框右侧的错误图标 */
.q-field--error .q-field__append .q-icon {
  display: none !important;
}

/* 移除错误状态下的红色 */
.q-field--error .q-field__label {
  color: rgba(0, 0, 0, 0.7) !important;
}

/* Ensure all form inputs have pure black text */
.q-form input,
.q-form textarea,
.q-form .q-field__native,
.q-form .q-field__prefix,
.q-form .q-field__suffix,
.q-form .q-field__input {
  color: #000000 !important;
  font-weight: 500;
}

/* Make selected dropdown options pure black */
.q-select__dropdown-item--selected,
.q-select .q-item--active {
  color: #000000 !important;
}

/* Styles for view mode field labels and values */
.field-label {
  color: rgba(0, 0, 0, 0.7);
  font-size: 14px;
  margin-bottom: 4px;
}

.field-value {
  color: #000000;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 0;
  min-height: 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  margin-bottom: 4px;
}

.field-value-multiline {
  white-space: pre-line;
  line-height: 1.5;
}

/* 添加小屏幕自适应样式 */
.exhibition-form-card {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 32px); /* 减去padding的高度 */
  max-height: calc(100vh - 32px);
  overflow: hidden;
}

.scroll-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

.fixed-bottom-actions {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  margin-top: auto;
}

/* 在小屏幕上增强底部按钮的可见性 */
@media (max-height: 600px) {
  .fixed-bottom-actions {
    position: sticky;
    bottom: 0;
    padding: 16px;
    border-top: 2px solid #e0e0e0;
  }
  
  .scroll-content {
    padding-bottom: 100px;
  }
  
  /* 确保按钮足够大，便于点击 */
  .fixed-bottom-actions .q-btn {
    min-height: 42px;
  }
}

/* 针对特别小的屏幕，进一步优化 */
@media (max-height: 480px) {
  .q-page {
    padding: 8px !important;
  }
  
  .exhibition-form-card {
    height: calc(100vh - 16px);
    max-height: calc(100vh - 16px);
  }
  
  .fixed-bottom-actions {
    background-color: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(4px);
  }
  
  /* 在超小屏幕上，可以添加一个指示器提示用户可以滚动 */
  .scroll-content:after {
    content: '';
    position: absolute;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    width: 40px;
    height: 4px;
    background-color: #e0e0e0;
    border-radius: 4px;
    opacity: 0.7;
    pointer-events: none;
  }
}

/* 滚动指示器样式 */
.scroll-indicator {
  position: fixed;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  z-index: 100;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
  animation: fadeInOut 3s infinite;
}

@keyframes fadeInOut {
  0%, 100% { opacity: 0.2; }
  50% { opacity: 0.8; }
}

/* 仅在小屏幕上显示滚动指示器 */
@media (min-height: 700px) {
  .scroll-indicator {
    display: none;
  }
}
</style>



